import { Cascader } from "antd";
import React, {useEffect, useState} from "react";
import { api } from "../../utils/constants";
import { toTree } from "../../utils/funtions";
import request from "../../utils/request";

export default function AreaRegion({ value, disabled, clearable, onChange }) {
  const [options, setOptions] = useState([]);

  const [myValue ,setMyValue] = useState(value)

  const triggerChange=(val)=>{
    setMyValue(val)
    if(onChange) {
      onChange(val[val.length-1])
    }
  }

  useEffect(() => {
    const getData = async () => {
      console.log(api.selectionRegionall)
      let res = await request.post(api.selectionRegionall,{code:''});
      console.log(res)
      if(!res) return;

      if (res.status == 0) {
        res.data.forEach((item) => {
          if (item.id.substring(0, item.id.length - 2) !== '45') {
            item.pid = item.id.substring(0, item.id.length - 2)
          }
        })
        console.log(toTree(res.data))
        setOptions(toTree(res.data));
      }
    };

    getData();
  }, []);

  return (
    <Cascader
    fieldNames={{value:'id',label:'name'}}
      options={options}
      value={myValue}
      disabled={disabled}
      allowClear={clearable}
      onChange={triggerChange}
      expandTrigger='hover'
      placeholder="请选择行政区划"
      changeOnSelect 
    />
  );
}
